package com.lagou.rpc.consumer.proxy;


import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.FactoryBean;

import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Properties;
import java.util.UUID;

@AllArgsConstructor
public class RpcProxyFactoryBean implements FactoryBean {

    private Class serviceClass;

    @Override
    public Object getObject() throws Exception {
        Properties properties = new Properties();
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
        properties.load(in);
        String serverIp = properties.getProperty("rpc.server.ip");
        Integer serverPort = Integer.valueOf(properties.getProperty("rpc.server.port"));

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[]{serviceClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //1.封装request请求对象
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId(UUID.randomUUID().toString());
                    rpcRequest.setClassName(method.getDeclaringClass().getName());
                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameterTypes(method.getParameterTypes());
                    rpcRequest.setParameters(args);
                    //2.创建RpcClient对象
                    RpcClient rpcClient = new RpcClient(serverIp, serverPort);
                    try {
                        //3.发送消息
                        Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                        RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                        if (rpcResponse.getError() != null) {
                            throw new RuntimeException(rpcResponse.getError());
                        }
                        //4.返回结果
                        Object result = rpcResponse.getResult();
                        return JSON.parseObject(result.toString(), method.getReturnType());
                    } catch (Exception e) {
                        throw e;
                    } finally {
                        rpcClient.close();
                    }

                }
            });
    }

    @Override
    public Class<?> getObjectType() {
        return serviceClass;

    }
}